/**
 * Created by CJB on 2017-02-17 10:12:41.
 */
strLengthValidator();//验证输入长度
isPhoneValidator();//isPhone:true
isEmailValidator();
autocompleteValidator();//验证自动填充
//邮箱验证
function isEmailValidator(){
    jQuery.validator.addMethod("isEmail", function(value,element) {
        if(value){
            var email = /^[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]*)*@[a-zA-Z0-9\-]+([\.][a-zA-Z0-9\-]+)+$/;   //邮箱
            return this.optional(element) || (email.test(value));
        }else{
            return true;
        }
    }, "请正确填写邮箱");
}

(function(){
	$(function () {
		setDefaultStatusRadio("addUserPhoneTable");
	    initAddWindow();
	    cloneDiv();
	    setGroupInfo();
	    initAddMoveGroundDialog();//选择用户要加入的群
	    //去除所有控件的虚线框
		removeBlur();
		
	});
	/**
	 * 添加时候设置有关群信息，用于后台判断是只有添加通讯录还是同时将人员加到群中
	 */
	function setGroupInfo(){
		var emptyGroundId = $("#groundId").val();
		var groundUserId = $("#groundUser"+emptyGroundId).val();
	}
	
	/**
	 * 初始化电话的添加删除
	 */
	function cloneDiv(){		
		$("#addPhone").click(function() {  // add为添加div的id
			post(getPath() + "app/dictionary/tree/" + "USER_PHONE",{},
					function(selectResult){	
						var allDivs = $("#phoneTd").find("div");
						var divTest = $("#phoneTd").find("div").last();
						var newDiv = divTest.clone(true);						
						var selectArr = new Array();
						var htmlStr1 = null;
						for(var j = 1; j < selectResult.length; j++){
							var item = selectResult[j];
							var flag = true;
							for(var i = 0; i < allDivs.length; i++){
								var $phoneDiv = $(allDivs[i]);
								var $select0 = $($phoneDiv.find("select")[0]);
								var type = $select0.val();																
									if(type == item.id){																				
										selectArr[i] = item;
										flag = false;
									}															
							}
							if(flag){
								htmlStr1 += "<option value='" + item.id + "'>" + item.name + "</option>";
							}
							} 						
						if(selectArr.length > 0){
							for(var i=0; i < selectArr.length; i++){
								var item = selectArr[i];
								htmlStr1 += "<option value='" + item.id + "'>" + item.name + "</option>";
							}
						}
						
						var $lastDiv = $(divTest);
						var $lastInput = $($lastDiv.find("input")[0]);
						var lastInputId = $lastInput.attr("id");
						var num = lastInputId.substring(5,8);
						$(newDiv.find("select")[0]).attr("id",("type"+(parseInt(num)+1)));
						$(newDiv.find("input")[0]).val("");
						$(newDiv.find("span")[1]).attr("id",("defaultStatus"+(parseInt(num)+1)))
						if($(newDiv.find("span")[1]).hasClass('selected')){
							$(newDiv.find("span")[1]).removeClass('selected');
						};
						
						$(newDiv.find("input")[0]).attr("id","phone"+(parseInt(num)+1));
						divTest.after(newDiv);
						//$("#" + selectId).html(htmlStr1);
						//console.log(htmlStr1);
						$(newDiv.find("select")[0]).html(htmlStr1);
					}
			);
	    });
		$(".btn-delete").click(function() { // del为删除input的id			
			if($("#phoneTd").find("div").length > 1)
				$(this).parent().remove();
		});
	
	}
	
	/**
	 * 初始化添加窗口
	 */
	function initAddWindow(){
		//判断是否是在群中点击的添加按钮
		var groupId=$("#groundId").val();
		if(groupId){
			$("#moveGroupIds").val(groupId);
			var groundName= $("#ground"+groupId).text();
			$("#moveGroupName").val(groundName);
			
		}
		//初始化时间控件
		initDate("birthday");
		//初始化字典表
		getDictionaryList("type1", "USER_PHONE", null, null);
	    //声明消息提示
	    var toolTips = new Object();
	
	    //设置表单验证
	    var validator = $("#addForm").validate({
	        rules:{
	        	nickname:{
	        		required:true,
	        		strMaxLenth:"255",
	        	},
	        	post:{
	        		strMaxLenth:"255"
	        	},
	        	address:{
	        		strMaxLenth:"255"
	        	},
	        	email:{
	        		isEmail:true
	        	},
	        	deptName:{
	        		autocomplete:["deptName","departmentId"]
	        	},
	        	remark:{
	        		strMaxLenth:"1000",
	        	},
	        	phone:{
	        		isPhone:true
	        	}
	        },
	        messages:{
	            
	        },
	        errorPlacement: function(eror,element){
	            var toolTip = createTooltip(toolTips,element.attr("id"));
	            toolTip.setContent(eror.text());
	            toolTip.close();
	            element.addClass("error-border");
	        },
	        success:function(label){
	            var elementId = label.attr("id").substring(0,label.attr("id").length - 6);
	            var toolTip = toolTips[elementId];
	            $("#" + elementId).removeClass("error-border");
	            toolTip.close();
	            toolTip.detach();
	        },
	        submitHandler:function(form){
	        	//获取电话信息
	        	var phoneDivs = $("#phoneTd").find("div");
	    		var phoneArr = new Array();		
	    		for ( var i = 0; i < phoneDivs.length; i++) {
	    			var $phoneDiv = $(phoneDivs[i]);
	    			var $select0 = $($phoneDiv.find("select")[0]);
	    			var type = $select0.val();
	    			var $input0 = $($phoneDiv.find("input")[0]);
	    			var phone = $input0.val();	
	    			var defaultStatus = 0;
	    			if($($phoneDiv.find("span")[1]).hasClass('selected')){
	    				defaultStatus = 1;
	    			}
	    			phoneArr.push({"type": type,"phone": phone,"defaultStatus":defaultStatus});			
	    		}
	    	//alert($("#addForm").serialize()+ "&phones=" + JSON.stringify(phoneArr)+"&groundId="+$("#groundId").val()+"&groundUserId="+$("#groundUserId").val());
	    		loadDiv.showLoading();
	        	post(getPath() + "base/userPhone/add",
	                $("#addForm").serialize()+ "&phones=" + JSON.stringify(phoneArr)+"&groundUserId="+$("#groundUserId").val(),
	                function(resultObject){
	                var errors = resultObject.errors;
	                var groundId = $("#groundId").val();
	                var groundUserId = $("#groundUserId").val();
	                var currentUserId = resultObject.currentUserId;
	                //判断后台是否有返回错误消息
	                if(errors && errors.length > 0){
	                	loadDiv.hideLoading();
	                    for(var i=0; i < errors.length; i++){
	                        var error = errors[i];
	                        var toolTip = createTooltip(toolTips,error.field);
	                        toolTip.setContent(error.defaultMessage);
	                        $("#" + error.field).addClass("error-border");
	                    }
	                }else{
	                    //添加成功，弹出添加成功提示框，当用户点击确定后刷新页面
	                	loadDiv.hideLoading();
	                	var groupIds = $("#moveGroupIds").val();
	                	if(groupIds){
	                		var groupIdsArr =  groupIds.split(",");
							for ( var i = 0; i < groupIdsArr.length; i++) {
								var oldPeolpeNum = $("#peopleNum"+groupIdsArr[i]).text();
								$("#peopleNum"+groupIdsArr[i]).text(parseInt(oldPeolpeNum) + 1);
							}
	                	}
	                	/*if(groundId && groundUserId == currentUserId && groundUserId.length > 0 ){
	                		createWindow("添加成功",{callBack:userAndPhoneCallBack}).dialog("open");
	                	}else{
	                	}*/
	                	createWindow("添加成功",{callBack:phoneCallBack}).dialog("open");
	                }
	        	},function(resultObject){
	        		loadDiv.hideLoading();
	        		createWindow(resultObject).dialog('open');
	        	});
	        }
	    });
	    //隐藏列表，显示添加
		$('#dialog').show();
		$('.grid-list').hide();

		//取消
		$('#cancleBtn').click(function(){
			$('#dialog').hide();
			$('.grid-list').show();
		});

		//任务
		setAutoComplete('deptName','departmentId',getPath() + 'org/department/list/select/5',{
			labelField:'name',
			valueField:'id'
		});
	}
	 function userAndPhoneCallBack(){
		 var groundId = $("#groundId").val();
		 var oldPeolpeNum = $("#peopleNum"+groundId).text();
		 $("#peopleNum"+groundId).text(parseInt(oldPeolpeNum) + 1);
		 $("#rightDiv").load(getPath()+"base/userPhone/list/1/"+pageSize);
	 }
	 
	 

})();
/**
 * 初始化移至分群
 */
function initAddMoveGroundDialog(){
	$("#addUserToGroup").click(function(){
			var everyGroupTitleUl ="<ul id='addMoveGroupTitleUl' style='padding-top: 0px;'>	</ul>"
			$("#addGroupDialog").html(everyGroupTitleUl);
			loadDiv.showLoading();
			post(getPath() + "mobile/ground/getAllCanMoveGroup",
					{},
					function(resultObject){
				var mobileGroundArr = resultObject.moveGroupList;
			//	console.log(mobileGroundArr.length);
				if(mobileGroundArr.length == 0){
					createWindow('您没有任何群。').dialog('open');
					loadDiv.hideLoading();
		            return ;  
				}else{
					var everyGroundTitleLi = "";
					for(var i=0;i<mobileGroundArr.length;i++){
						everyGroundTitleLi += "<li id='li"+mobileGroundArr[i].id+"' onclick='addMoveGroundOnClick("+mobileGroundArr[i].id+")'>" ;
						/*if(groundId && mobileGroundArr[i].id == groundId ){
							everyGroundTitleLi += "<span id='"+mobileGroundArr[i].id+"'class='checkbox selected'></span>";
						}else{
						}*/
						everyGroundTitleLi += "<span id='"+mobileGroundArr[i].id+"'class='checkbox' style='float:left;margin-top:3px'></span>";
						everyGroundTitleLi += " <span id='#ground"+mobileGroundArr[i].id+"' class='groundName' style='margin-left: 20px'>"+mobileGroundArr[i].name+"</span></li>";																				
					}
					$("#addMoveGroupTitleUl").html(everyGroundTitleLi);
					
					var groupIds = $("#moveGroupIds").val();
					if(groupIds){
						var groupIdsArr =  groupIds.split(",");
						for ( var i = 0; i < groupIdsArr.length; i++) {
							var selectSpan = $("#"+groupIdsArr[i]);
							selectSpan.addClass('selected');
						}
					}
					addMoveGroupWindow("addGroupDialog","选择群",{width:300}).dialog("open");
					loadDiv.hideLoading();
				}
			});
		
	});
}
function addMoveGroundOnClick(spanId){
	var selectSpan = $("#"+spanId);
	if(!selectSpan.hasClass('selected')){
		selectSpan.addClass('selected');
	}else{
		selectSpan.removeClass('selected');
	}
}

/**
 * 创建移至分群弹出框
 */
function addMoveGroupWindow(id, label,options){
	options = $.extend({
        width: 400,
        height: 300
    },options || {});
	//初始化添加窗口
    var addWindow = $("#" + id);
    addWindow.dialog({
        autoOpen: false,
        width: options.width,
        height: options.height,
        resizable: false,
        title: label,
        modal: true,
        buttons: {
            "确定": function () {
                var groundList = new Array();
                var groundNameList = new Array();
                $("#addGroupDialog ul li span.checkbox").each(function () {
                    if ($(this).hasClass('selected')){
                    	groundList[groundList.length] = $(this).attr("id");
                    	groundNameList[groundNameList.length] = $(this).next().text();
                    }
                });
                var groundIds = groundList.join( "," );
                var groupNames = groundNameList .join( "," );
                $("#moveGroupIds").val(groundIds);
                $("#moveGroupName").val(groupNames);
                $("#moveGroupName").attr("title",groupNames);
                $(this).dialog("close");
                $(this).empty();
            },
            "取消": function () {
                $(this).dialog("close");
                $(this).empty();
            }
        },
        close: function(){
        	$(".jBox-wrapper").remove();
        	$(this).empty();
        }
    });
    return addWindow;
}